package cn.itcast.openai;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

/**
 * @author wys
 * @version V1.0
 * @date 2025-04-19 17:27
 */
public class CompletionsStreamingDemo {
    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.builder()
                // .baseUrl("https://api.chatanywhere.tech/v1")
                // .apiKey(System.getenv("OPENAI_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .build();

        ChatCompletionCreateParams createParams = ChatCompletionCreateParams.builder()
                .model("qwen-plus")
                .addSystemMessage("你是java之父")
                .addUserMessage("java之父是于胜军吗")
                .build();

        try (var response = client.chat().completions().createStreaming(createParams)) {
            response.stream()
                    .flatMap(chatCompletionChunk -> chatCompletionChunk.choices().stream())
                    .flatMap(choice -> choice.delta().content().stream())
                    .forEach(System.out::println);
        }
    }
}
